from django.contrib.auth.models import User
from jwt import DecodeError
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework_jwt.authentication import jwt_decode_handler
from accounts.serializers import *
from utils.response import *
from drf_yasg import openapi
from drf_yasg.utils import swagger_auto_schema


class UserInfo(APIView):
    Token = openapi.Parameter('Token', required=True, in_=openapi.IN_HEADER, description='Token',
                              type=openapi.TYPE_STRING)

    @swagger_auto_schema(
        manual_parameters=[Token],
        responses={
            '200': openapi.Response('', infoSerializers)
        },
        security=[],
        operation_id='获取账户信息',
        operation_description=
        """
        根据token判断账户类型：学生账号返回学生个人信息,教师账号返回教师个人信息
        """
    )
    def post(self, request):
        if request.method == 'POST':
            token = request.META.get('HTTP_TOKEN')
            try:
                toke_user = []
                # 顶一个空数组来接收token解析后的值
                toke_user = jwt_decode_handler(token)
                # 获得user_id
            except DecodeError:
                nothing['error'] = '账号验证不通过请重新登录'
                return Response(nothing)
            user_id = toke_user["user_id"]
            # 通过user_id查询用户信息
            user = User.objects.get(pk=user_id)
            # 判断登录账户是否在学生表中，给出对应格式信息
            roles = []
            if user.is_superuser:
                roles.append('SuperAdmin')
            elif user.is_active and not user.is_superuser:
                roles.append('Admin')
            else:
                roles.append('User')
            owner = Info.objects.get(owner=user)
            obj = Station.objects.get(info__id=owner.id)
            if obj.name == '学生':
                roles.append('student')
                student_info = Info.objects.get(owner=user)
                count = Info.objects.filter(owner=user).count()
                serializer = infoSerializers(student_info)
                response['total'] = count
                response['data'] = serializer.data
                response['data']['roles'] = roles
                return Response(response)
            elif obj.name == '教师':
                roles.append('teacher')
                teacher_info = Info.objects.get(owner=user)
                count = Info.objects.filter(owner=user).count()
                serializer = TeacherSerializers(teacher_info)
                response['total'] = count
                response['data'] = serializer.data
                response['data']['roles'] = roles
                return Response(response)
            else:
                nothing['error'] = '没有找到该账户用户信息'
                return Response(nothing)


class ClassInfo(APIView):
    Token = openapi.Parameter('Token', required=True, in_=openapi.IN_HEADER, description='Token',
                              type=openapi.TYPE_STRING)

    @swagger_auto_schema(
        manual_parameters=[Token],
        responses={
            '200': openapi.Response('', ClassSerializers)
        },
        security=[],
        operation_id='获取班级信息',
        operation_description=
        """
        查看自己所在班级
        """
    )
    def post(self, request):
        if request.method == 'POST':
            token = request.META.get('HTTP_TOKEN')
            try:
                toke_user = []
                toke_user = jwt_decode_handler(token)
                user_id = toke_user["user_id"]
                user = User.objects.get(pk=user_id)
                owner = Info.objects.get(owner=user)
            except DecodeError:
                nothing['error'] = '账号验证不通过请重新登录'
                return Response(nothing)
            except Info.DoesNotExist:
                nothing['error'] = '没有找到该账户的班级信息'
                return Response(nothing)
            else:
                classes_info = Dept.objects.filter(info__id=owner.id)
                print(classes_info)
                classes_count = classes_info.count()
                serializer = ClassSerializers(classes_info, many=True)
                response['data'] = serializer.data
                response['total'] = classes_count
                return Response(response)


class Classmate(APIView):
    Id = openapi.Parameter('id', required=True, in_=openapi.IN_QUERY, description='id',
                           type=openapi.TYPE_STRING)

    @swagger_auto_schema(
        manual_parameters=[Id],
        responses={
            '200': openapi.Response('', infoSerializers)
        },
        security=[],
        operation_id='获取班级学生信息',
        operation_description='返回班级所有学生信息',
    )
    def get(self, request):
        if request.method == 'GET':
            data = request.GET.get('id')
            try:
                Dept.objects.get(id=data)
            except Dept.DoesNotExist:
                nothing['error'] = '没有找到对应班级的信息'
                return Response(nothing)
            else:
                student = Info.objects.filter(dept__id=data, station__id=1)
                student_count = student.count()
                serializer = infoSerializers(student, many=True)
                response['data'] = serializer.data
                response['total'] = student_count
                return Response(response)


class StudentInfo(APIView):
    Id = openapi.Parameter('id', required=True, in_=openapi.IN_QUERY, description='id',
                           type=openapi.TYPE_STRING)

    @swagger_auto_schema(
        manual_parameters=[Id],
        responses={
            '200': openapi.Response('', infoSerializers)
        },
        security=[],
        operation_id='获取学生个人信息',
        operation_description='返回学生信息',
    )
    def get(self, request):
        if request.method == 'GET':
            data = request.GET.get('id')
            try:
                student = Info.objects.get(id=data, station__id=1)
            except Info.DoesNotExist:
                nothing['error'] = '没有找到此学生信息'
                return Response(nothing)
            else:
                serializer = infoSerializers(student)
                response['data'] = serializer.data
                return Response(response)


class DepartmentAPI(APIView):
    @swagger_auto_schema(
        responses={
            '200': openapi.Response('', DepartmentSerializers)
        },
        security=[],
        operation_id='学校社团信息',
        operation_description='获取学校社团信息',
    )
    def get(self, request):
        queryset = Dept.objects.filter(label__id=1)
        serializer = DepartmentSerializers(queryset, many=True)
        department_count = queryset.count()
        response['total'] = department_count
        response['data'] = serializer.data
        return Response(response)
